<?php
/**
 * 语法检查系统测试脚本
 * Syntax Checker System Test Script
 * 
 * @package WP Bootstrap Woo
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * 语法检查系统测试类
 */
class WBW_Syntax_Checker_Test {
    
    private $test_results = array();
    
    public function __construct() {
        $this->run_all_tests();
    }
    
    /**
     * 运行所有测试
     */
    public function run_all_tests() {
        echo "<div style='padding: 20px; font-family: Arial, sans-serif;'>";
        echo "<h2>🔧 WordPress主题语法检查系统测试</h2>";
        
        $this->test_file_scanner();
        $this->test_syntax_checker();
        $this->test_performance_checker();
        $this->test_auto_fix_engine();
        $this->test_database_manager();
        
        $this->display_summary();
        echo "</div>";
    }
    
    /**
     * 测试文件扫描器
     */
    private function test_file_scanner() {
        echo "<h3>📁 测试文件扫描器</h3>";
        
        try {
            require_once get_template_directory() . '/inc/template-file-scanner.php';
            $scanner = new WBW_Template_File_Scanner();
            
            // 测试核心模板扫描
            $core_templates = $scanner->get_core_templates();
            $this->add_test_result('文件扫描器初始化', true);
            $this->add_test_result('核心模板扫描 (' . count($core_templates) . ' 个文件)', true);
            
            // 测试WooCommerce模板扫描
            $woo_templates = $scanner->get_woocommerce_templates();
            $this->add_test_result('WooCommerce模板扫描 (' . count($woo_templates) . ' 个文件)', true);
            
            // 测试统计信息
            $stats = $scanner->get_file_statistics();
            $this->add_test_result('文件统计信息生成', isset($stats['total_files']));
            
        } catch (Exception $e) {
            $this->add_test_result('文件扫描器测试失败', false, $e->getMessage());
        }
    }
    
    /**
     * 测试语法检查器
     */
    private function test_syntax_checker() {
        echo "<h3>✅ 测试语法检查器</h3>";
        
        try {
            require_once get_template_directory() . '/inc/syntax-checker.php';
            $checker = new WBW_Syntax_Checker();
            
            $this->add_test_result('语法检查器初始化', true);
            
            // 创建测试文件
            $test_file = $this->create_test_file();
            if ($test_file) {
                $this->add_test_result('测试文件创建', true);
                
                // 清理测试文件
                unlink($test_file);
                $this->add_test_result('测试文件清理', true);
            }
            
        } catch (Exception $e) {
            $this->add_test_result('语法检查器测试失败', false, $e->getMessage());
        }
    }
    
    /**
     * 测试性能检查器
     */
    private function test_performance_checker() {
        echo "<h3>⚡ 测试性能检查器</h3>";
        
        try {
            require_once get_template_directory() . '/inc/performance-checker.php';
            $checker = new WBW_Performance_Checker();
            
            $this->add_test_result('性能检查器初始化', true);
            
            // 测试性能检查
            $results = $checker->run_performance_check();
            $this->add_test_result('性能检查执行', isset($results['performance_score']));
            $this->add_test_result('优化建议生成', isset($results['optimization_suggestions']));
            
        } catch (Exception $e) {
            $this->add_test_result('性能检查器测试失败', false, $e->getMessage());
        }
    }
    
    /**
     * 测试自动修复引擎
     */
    private function test_auto_fix_engine() {
        echo "<h3>🔧 测试自动修复引擎</h3>";
        
        try {
            require_once get_template_directory() . '/inc/auto-fix-engine.php';
            $engine = new WBW_Auto_Fix_Engine();
            
            $this->add_test_result('自动修复引擎初始化', true);
            
            // 测试备份功能
            $test_file = $this->create_test_file();
            if ($test_file) {
                $backup_path = $engine->create_backup($test_file);
                $this->add_test_result('文件备份创建', !empty($backup_path));
                
                if ($backup_path && file_exists($backup_path)) {
                    unlink($backup_path);
                    $this->add_test_result('备份文件清理', true);
                }
                
                unlink($test_file);
            }
            
        } catch (Exception $e) {
            $this->add_test_result('自动修复引擎测试失败', false, $e->getMessage());
        }
    }
    
    /**
     * 测试数据库管理器
     */
    private function test_database_manager() {
        echo "<h3>🗄️ 测试数据库管理器</h3>";
        
        try {
            require_once get_template_directory() . '/inc/database-manager.php';
            $db_manager = new WBW_Database_Manager();
            
            $this->add_test_result('数据库管理器初始化', true);
            
            // 测试配置读写
            $test_key = 'test_config_' . time();
            $test_value = 'test_value_' . rand(1000, 9999);
            
            $set_result = $db_manager->set_config($test_key, $test_value, 'Test configuration');
            $this->add_test_result('配置写入', $set_result !== false);
            
            $get_result = $db_manager->get_config($test_key);
            $this->add_test_result('配置读取', $get_result === $test_value);
            
        } catch (Exception $e) {
            $this->add_test_result('数据库管理器测试失败', false, $e->getMessage());
        }
    }
    
    /**
     * 创建测试文件
     */
    private function create_test_file() {
        $upload_dir = wp_upload_dir();
        $test_content = "<?php\n// Test file\necho 'Hello World';\n";
        $test_file = $upload_dir['basedir'] . '/test_syntax_' . time() . '.php';
        
        if (file_put_contents($test_file, $test_content)) {
            return $test_file;
        }
        
        return false;
    }
    
    /**
     * 添加测试结果
     */
    private function add_test_result($test_name, $success, $error_message = '') {
        $this->test_results[] = array(
            'name' => $test_name,
            'success' => $success,
            'error' => $error_message
        );
        
        $icon = $success ? '✅' : '❌';
        $color = $success ? 'green' : 'red';
        
        echo "<p style='color: {$color}; margin: 5px 0;'>";
        echo "{$icon} {$test_name}";
        if (!$success && $error_message) {
            echo " - 错误: {$error_message}";
        }
        echo "</p>";
    }
    
    /**
     * 显示测试摘要
     */
    private function display_summary() {
        $total_tests = count($this->test_results);
        $passed_tests = count(array_filter($this->test_results, function($r) { return $r['success']; }));
        $failed_tests = $total_tests - $passed_tests;
        
        echo "<div style='background: #f1f1f1; padding: 15px; border-radius: 5px; margin-top: 20px;'>";
        echo "<h3>📊 测试摘要</h3>";
        echo "<p><strong>总测试数:</strong> {$total_tests}</p>";
        echo "<p style='color: green;'><strong>通过:</strong> {$passed_tests}</p>";
        echo "<p style='color: red;'><strong>失败:</strong> {$failed_tests}</p>";
        
        $success_rate = $total_tests > 0 ? round(($passed_tests / $total_tests) * 100, 2) : 0;
        echo "<p><strong>成功率:</strong> {$success_rate}%</p>";
        
        if ($failed_tests === 0) {
            echo "<p style='color: green; font-weight: bold;'>🎉 所有测试通过！语法检查系统已准备就绪。</p>";
        } else {
            echo "<p style='color: orange; font-weight: bold;'>⚠️ 部分测试失败，请检查上述错误信息。</p>";
        }
        
        echo "</div>";
        
        // 显示使用说明
        echo "<div style='background: #e3f2fd; padding: 15px; border-radius: 5px; margin-top: 20px;'>";
        echo "<h3>📖 使用说明</h3>";
        echo "<p>语法检查系统已成功安装！您现在可以：</p>";
        echo "<ul>";
        echo "<li>访问 <strong>外观 > 语法检查</strong> 使用管理界面</li>";
        echo "<li>运行完整的模板文件语法检查</li>";
        echo "<li>检查和优化网站性能设置</li>";
        echo "<li>使用自动修复功能处理常见语法错误</li>";
        echo "<li>查看详细的检查历史和统计信息</li>";
        echo "</ul>";
        echo "</div>";
    }
}

// 如果是管理员且在测试页面，运行测试
if (current_user_can('manage_options') && isset($_GET['wbw_test_syntax_checker'])) {
    new WBW_Syntax_Checker_Test();
}